const express = require('express')
const jwt = require('jsonwebtoken')
const { User } = require('../models')
const router = express.Router()

// 注册
router.post('/register', async (req, res) => {
  try {
    const { username, email, password, name, phone, company, department } = req.body
    
    // 检查用户是否已存在
    const existingUser = await User.findOne({
      where: {
        $or: [{ email }, { username }]
      }
    })
    
    if (existingUser) {
      return res.status(400).json({ message: '用户已存在' })
    }
    
    const user = await User.create({
      username,
      email,
      password,
      name,
      phone,
      company,
      department
    })
    
    const token = jwt.sign(
      { userId: user.id, role: user.role },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES_IN }
    )
    
    res.json({
      message: '注册成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        name: user.name,
        role: user.role
      }
    })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 登录
router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body
    
    const user = await User.findOne({ where: { email } })
    
    if (!user || !await user.comparePassword(password)) {
      return res.status(401).json({ message: '邮箱或密码错误' })
    }
    
    if (!user.isActive) {
      return res.status(403).json({ message: '账户已被禁用' })
    }
    
    // 更新最后登录时间
    await user.update({ lastLoginAt: new Date() })
    
    const token = jwt.sign(
      { userId: user.id, role: user.role },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRES_IN }
    )
    
    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        name: user.name,
        role: user.role,
        avatar: user.avatar
      }
    })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 获取用户信息
router.get('/userinfo', async (req, res) => {
  try {
    const token = req.headers.authorization?.split(' ')[1]
    
    if (!token) {
      return res.status(401).json({ message: '未提供token' })
    }
    
    const decoded = jwt.verify(token, process.env.JWT_SECRET)
    const user = await User.findByPk(decoded.userId, {
      attributes: { exclude: ['password'] }
    })
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    
    res.json({ user })
  } catch (error) {
    res.status(401).json({ message: 'token无效' })
  }
})

module.exports = router
